<template>
  <div class="settings-management-container">
    <h2>系统设置</h2>

    <el-tabs v-model="activeTab" class="settings-tabs">
      <el-tab-pane label="基础设置" name="basic">
        <el-form
          ref="basicSettingsFormRef"
          :model="settingsForm"
          label-width="150px"
          class="settings-form"
          v-loading="loading"
        >
          <el-card shadow="never" class="setting-card">
            <el-form-item label="站点名称" prop="siteTitle">
              <el-input v-model="settingsForm.siteTitle" placeholder="请输入站点名称"></el-input>
            </el-form-item>
            <el-form-item label="站点 Logo URL" prop="siteLogoUrl">
              <el-input v-model="settingsForm.siteLogoUrl" placeholder="请输入 Logo 图片的 URL"></el-input>
              <el-image v-if="settingsForm.siteLogoUrl" :src="settingsForm.siteLogoUrl" fit="contain" style="width: 100px; height: 50px; margin-top: 10px;"></el-image>
            </el-form-item>
            <el-form-item label="允许新用户注册" prop="allowRegistration">
              <el-switch v-model="settingsForm.allowRegistration"></el-switch>
            </el-form-item>
            <el-form-item label="新用户默认角色" prop="defaultUserRole">
              <el-select v-model="settingsForm.defaultUserRole" placeholder="请选择">
                <el-option label="普通用户" value="user"></el-option>
                <el-option label="管理员" value="admin"></el-option>
              </el-select>
            </el-form-item>
          </el-card>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="视频设置" name="video">
        <el-form
          ref="videoSettingsFormRef"
          :model="settingsForm"
          label-width="180px"
          class="settings-form"
          v-loading="loading"
        >
          <el-card shadow="never" class="setting-card">
            <el-form-item label="最大上传视频大小 (MB)" prop="maxVideoFileSize">
              <el-input-number v-model="settingsForm.maxVideoFileSize" :min="1" placeholder="MB"></el-input-number>
            </el-form-item>
            <el-form-item label="允许上传的视频格式" prop="allowedVideoFormats">
              <el-input v-model="settingsForm.allowedVideoFormats" placeholder="例如: mp4,avi,mov (用逗号分隔)"></el-input>
            </el-form-item>
            <el-form-item label="自动转码" prop="autoTranscode">
              <el-switch v-model="settingsForm.autoTranscode" disabled title="此功能已在后端移除"></el-switch>
              <span class="setting-tip"> (视频转码功能已在后端移除)</span>
            </el-form-item>
          </el-card>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="邮件设置 (SMTP)" name="email">
        <el-form
          ref="emailSettingsFormRef"
          :model="settingsForm"
          label-width="180px"
          class="settings-form"
          v-loading="loading"
        >
          <el-card shadow="never" class="setting-card">
            <el-form-item label="SMTP 主机" prop="smtpHost">
              <el-input v-model="settingsForm.smtpHost" placeholder="例如: smtp.example.com"></el-input>
            </el-form-item>
            <el-form-item label="SMTP 端口" prop="smtpPort">
              <el-input-number v-model="settingsForm.smtpPort" :min="1" :max="65535"></el-input-number>
            </el-form-item>
            <el-form-item label="SMTP 用户名" prop="smtpUser">
              <el-input v-model="settingsForm.smtpUser" placeholder="邮箱账号"></el-input>
            </el-form-item>
            <el-form-item label="SMTP 密码/授权码" prop="smtpPass">
              <el-input type="password" v-model="settingsForm.smtpPass" placeholder="输入密码或授权码" show-password></el-input>
            </el-form-item>
            <el-form-item label="发件人邮箱" prop="smtpFrom">
              <el-input v-model="settingsForm.smtpFrom" placeholder="显示在邮件中的发件人地址"></el-input>
            </el-form-item>
            <el-form-item label="启用 TLS/SSL" prop="smtpSecure">
              <el-switch v-model="settingsForm.smtpSecure"></el-switch>
            </el-form-item>
          </el-card>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <div class="form-actions">
      <el-button type="primary" @click="saveSettings" :loading="saving">保存设置</el-button>
      <el-button @click="resetForm">重置</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from '@/services/axios';
import { ElMessage } from 'element-plus';
import { useStore } from 'vuex';

const store = useStore();
const activeTab = ref('basic'); // 控制当前激活的标签页

// 将表单引用拆分到每个标签页
const basicSettingsFormRef = ref(null);
const videoSettingsFormRef = ref(null);
const emailSettingsFormRef = ref(null);

const loading = ref(false);
const saving = ref(false);

// 定义设置表单的数据结构，与后端对应
const settingsForm = reactive({
  siteTitle: '',
  siteLogoUrl: '',
  allowRegistration: true,
  defaultUserRole: 'user',
  maxVideoFileSize: 1024, // 默认 1GB
  allowedVideoFormats: 'mp4,mov,avi,wmv',
  autoTranscode: false, // 默认为 false，因为后端已移除
  smtpHost: '',
  smtpPort: 587,
  smtpUser: '',
  smtpPass: '',
  smtpFrom: '',
  smtpSecure: true, // 默认启用 TLS
  // 可以根据需要添加更多设置项
});

// 从后端加载设置
const loadSettings = async () => {
  loading.value = true;
  try {
    const response = await axios.get('/api/admin/settings');
    console.log('加载系统设置响应:', response.data); // 添加日志以便调试
    
    // 检查响应中是否包含设置数据
    if (response.data && response.data._id) {
      const settings = response.data;
      settingsForm.siteTitle = settings.siteName || '';
      settingsForm.siteLogoUrl = settings.logo || '';
      settingsForm.allowRegistration = !!settings.enableRegistration;
      settingsForm.defaultUserRole = settings.defaultUserRole || 'user';
      settingsForm.maxVideoFileSize = settings.maxVideoSize || 1024;
      settingsForm.allowedVideoFormats = (settings.allowedVideoFormats || ['mp4', 'webm']).join(',');
      settingsForm.autoTranscode = false;
      
      // 处理邮件设置
      if (settings.emailConfig) {
        settingsForm.smtpHost = settings.emailConfig.host || '';
        settingsForm.smtpPort = settings.emailConfig.port || 587;
        settingsForm.smtpUser = settings.emailConfig.user || '';
        settingsForm.smtpPass = settings.emailConfig.pass || '';
        settingsForm.smtpFrom = settings.emailConfig.from || '';
        settingsForm.smtpSecure = !!settings.emailConfig.secure;
      }
      
      console.log('系统设置加载成功'); // 添加成功日志
      ElMessage.success('系统设置加载成功');
      return;
    }

    // 如果没有找到设置数据
    await saveSettings();
  } catch (error) {
    console.error('', error);
    if (error.response?.status === 401) {
      ElMessage.error('请先登录');
    } else if (error.response?.status === 403) {
      ElMessage.error('没有权限访问系统设置');
    } else {
      ElMessage.error('加载系统设置失败，请检查网络连接');
    }
  } finally {
    loading.value = false;
  }
};

// 保存设置到后端
const saveSettings = async () => {
  saving.value = true;
  try {
    // 处理视频格式数组
    const videoFormats = settingsForm.allowedVideoFormats
      .split(',')
      .map(format => format.trim())
      .filter(format => ['mp4', 'webm', 'avi', 'mov', 'flv'].includes(format));

    if (videoFormats.length === 0) {
      videoFormats.push('mp4', 'webm'); // 使用默认格式
    }

    // 准备要发送的数据
    const payload = {
      siteName: settingsForm.siteTitle || '我的个人网站',
      siteDescription: '这是一个视频分享平台',
      icpNumber: '',
      maxVideoSize: Math.min(Math.max(Number(settingsForm.maxVideoFileSize) || 500, 1), 10000),
      allowedVideoFormats: videoFormats,
      enableComments: true,
      commentNeedsReview: true,
      commentInterval: 30,
      enableRegistration: settingsForm.allowRegistration,
      defaultUserRole: settingsForm.defaultUserRole || 'user',
      defaultUserStatus: 'active',
      videoNeedsReview: true,
      defaultVideoStatus: 'pending',
      enableVideoDownload: false,
      storageType: 'local',
      storageConfig: {},
      emailConfig: {
        host: settingsForm.smtpHost || '',
        port: Math.min(Math.max(Number(settingsForm.smtpPort) || 587, 1), 65535),
        user: settingsForm.smtpUser || '',
        pass: settingsForm.smtpPass || '',
        from: settingsForm.smtpFrom || '',
        secure: settingsForm.smtpSecure
      },
      enableCache: true,
      cacheExpiration: 3600,
      autoBackup: false,
      backupInterval: 86400,
      maxBackupFiles: 10
    };

    console.log('保存系统设置，发送数据:', payload); // 添加请求日志

    const response = await axios.put('/api/admin/settings', payload);
    console.log('保存系统设置响应:', response.data); // 添加响应日志

    if (response.data?.success) {
      ElMessage.success('系统设置保存成功!');
      
      // 重新获取用户信息以更新头像
      try {
        const userResponse = await axios.get('/api/user/profile');
        if (userResponse.data?.success) {
          store.commit('auth/SET_USER', userResponse.data.user);
          console.log('用户信息已更新');
        }
      } catch (error) {
        console.error('更新用户信息失败:', error);
      }
      
      return;
    }

    // 如果没有返回 success 为 true，说明保存失败
    const errorMsg = response.data?.message || '保存设置失败';
    console.error('保存失败:', errorMsg); // 添加错误日志
    ElMessage.error(errorMsg);
  } catch (error) {
    console.error('保存系统设置失败:', error);
    if (error.response?.status === 401) {
      ElMessage.error('请先登录');
    } else if (error.response?.status === 403) {
      ElMessage.error('没有权限修改系统设置');
    } else {
      ElMessage.error(error.response?.data?.message || '保存系统设置失败，请检查网络连接');
    }
  } finally {
    saving.value = false;
  }
};

// 重置表单（重新从后端加载）
const resetForm = () => {
  loadSettings();
  ElMessage.info('设置已重置为上次保存的状态');
};

// 组件挂载时加载设置
onMounted(() => {
  loadSettings();
});

</script>

<style scoped>
.settings-management-container {
  padding: 20px;
}

h2 {
  text-align: center;
  margin-bottom: 30px;
}

.settings-tabs {
  max-width: 900px; /* 可以适当调整宽度 */
  margin: 0 auto 20px; /* 调整外边距 */
}

.settings-form {
  /* 移除 max-width 和 margin，因为宽度由 tabs 控制 */
}

.setting-card {
  border: none; /* 移除卡片边框，因为在 Tab 内 */
  box-shadow: none; /* 移除卡片阴影 */
  margin-bottom: 0; /* 移除卡片底部外边距 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.setting-tip {
  color: #909399;
  font-size: 12px;
  margin-left: 10px;
}

.form-actions {
  text-align: center; /* 按钮居中 */
  margin-top: 30px; /* 增加顶部外边距 */
}
</style>